﻿using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Security;
using System.Web.UI.WebControls;
using EmptyWallGallery.Core;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.FrontEnd.inside.Tools
{
    public partial class SlideShow : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;

            if (Request.QueryString["action"] == "Delete")
            {
                if (DeleteSlide(int.Parse(Request.QueryString["ID"])))
                {
                    Response.Redirect("SlideShow.aspx");
                }
            }
            else
            {
                //BindDrop();
                BindGrid();                
            }
        }

        private void BindGrid()
        {
            grdListArticle.DataSource = Core.BLL.SlideShow.Instance.GetAllSlide(2);
            grdListArticle.DataBind();
            grdListArticle.GridLines = GridLines.None;
        }

        protected void BtnApplyClick(object sender, EventArgs e)
        {
            if (Request.Form["selectedAction0"] == "3" || Request.Form["selectedAction1"] == "3")
            {
                foreach (var s in
                    Regex.Split(Request.Form["cboCheckArticle"], ",").Where(s => Common.Instance.IsNumeric(s)))
                {
                    if (DeleteSlide(int.Parse(s)))
                    {
                        lblError.InnerHtml += "* Slide " + s + " đã được xóa !!<br />";
                    }
                    else
                    {
                        lblError.InnerHtml += "* Slide " + s + " xóa không thành công !!<br />";
                    }
                }
            }
            else if (Request.Form["selectedAction0"] == "1" || Request.Form["selectedAction1"] == "1")
            {
                foreach (var s in
                    Regex.Split(Request.Form["cboCheckArticle"], ",").Where(s => Common.Instance.IsNumeric(s)))
                {
                    if (UpdateStatus(int.Parse(s), true))
                    {
                        lblError.InnerHtml += "* Slide " + s + " đã được hiển thị !!<br />";
                    }
                    else
                    {
                        lblError.InnerHtml += "* Slide " + s + " chuyển trạng thái không thành công !!<br />";
                    }
                }
            }
            else if (Request.Form["selectedAction0"] == "2" || Request.Form["selectedAction1"] == "2")
            {
                foreach (var s in
                    Regex.Split(Request.Form["cboCheckArticle"], ",").Where(s => Common.Instance.IsNumeric(s)))
                {
                    if (UpdateStatus(int.Parse(s), false))
                    {
                        lblError.InnerHtml += "* Slide " + s + " không hiển thị !!<br />";
                    }
                    else
                    {
                        lblError.InnerHtml += "* Slide " + s + " chuyển trạng thái không thành công !!<br />";
                    }
                }
            }
            BindGrid();
        }

        private static bool DeleteSlide(int slideId)
        {
            if (Core.BLL.SlideShow.Instance.Delete(slideId))
            {
                if (Core.BLL.SlideShow.Instance.WriteSlideItem())
                {
                    return true;
                }
            }
            return false;
        }

        private static bool UpdateStatus(int slideId, bool status)
        {
            if (Core.BLL.SlideShow.Instance.UpdateStatus(slideId, status))
            {
                if (Core.BLL.SlideShow.Instance.WriteSlideItem())
                {
                    return true;
                }
            }
            return false;
        }

        protected void BtnApply2Click(object sender, EventArgs e)
        {
            BtnApplyClick(sender, e);
        }

        protected string DisplayTitle(string imageDesc, int i)
        {
            return Common.Instance.Truncate(imageDesc, i, true, true);
        }

        protected string DisplayStatusDate(string createDate, string status)
        {
            var dDate = DateTime.Parse(createDate).AddHours(Configs.TimeLine);
            return string.Format("{0:dd/MM/yyyy}", dDate) + "<br />" + (Boolean.Parse(status) ? "Đang hiển thị" : "Đang ẩn");
        }

        protected string DisplayCreateBy(string createBy)
        {
            var user = Membership.GetUser(new Guid(createBy));
            return user != null ? user.UserName : null;
        }

        protected string DisplayImage(string imageUrl)
        {
            return "<img src='" + Configs.HomeUrl + "Uploads/" + imageUrl + "' width='130' />";
        }

        protected void GrdListArticlePageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdListArticle.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void BtnUploadClick(object sender, EventArgs e)
        {
            try
            {
                var membershipUser = Membership.GetUser();
                if (membershipUser == null) return;
                if (membershipUser.ProviderUserKey == null) return;
                var strDesc = Common.Instance.NoHtml(txtDescription.Text);

                if (!fileUpload.HasFile) return;
                if (!Common.Instance.IsValidFile(fileUpload.PostedFile, new[] { "png", "gif", "jpg" })) return;

                var randomStr = new RandomStrings();
                var strFileName = randomStr.GenerateRandomString(DateTime.Now) + ".jpg";
                var strFolder = string.Format("{0}{1}\\{2}\\{3}\\{4}\\", Configs.UserFolder,
                                              membershipUser.UserName, DateTime.Now.Year,
                                              Common.Instance.Right("0" + DateTime.Now.Month, 2),
                                              Common.Instance.Right("0" + DateTime.Now.Day, 2));

                if (!Directory.Exists(strFolder))
                {
                    Directory.CreateDirectory(strFolder);
                }

                var objImage = new ImageUtil(fileUpload.PostedFile.InputStream, 1024, 1024, "UploadService",
                                             membershipUser.UserName,
                                             strFileName, 80);

                objImage.PublicUpload(130, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(486, 0, strFileName, 100, "", strFolder);

                var imagePath = strFolder.Replace(Configs.UserFolder, "").Replace("\\", "/") + "130x0__" + strFileName;

                if (Core.BLL.SlideShow.Instance.Create(strDesc, imagePath, true, membershipUser.ProviderUserKey.ToString()))
                {
                    if (Core.BLL.SlideShow.Instance.WriteSlideItem())
                    {
                        Response.Redirect("SlideShow.aspx", false);
                    }
                }
                else
                {
                    lblError.InnerHtml += "* Đã có lỗi trong quá trình thêm slide !!<br />";
                }
            }
            catch (Exception exception)
            {
            }
        }
    }
}